package com.example.lenovo.asia5b.home.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.activity.CommodityDetActivity;
import com.example.lenovo.asia5b.home.bean.ShopingCartBean;
import com.example.lenovo.asia5b.home.fragment.MianShopingCartFragment;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.keyboardUtil;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.wushi.lenovo.asia5b.R.id.edit_count;


/**
 * Created by lenovo on 2017/6/20.
 */

public class MianShopingCartAdapter extends BaseAdapter implements ICallBack
{

    private LayoutInflater mInflater;
    public List<ShopingCartBean> listBeans;
    public MianShopingCartFragment fragment;
    public boolean isVisibilityTit ;
    private Context context;
    //定义成员变量mTouchItemPosition,用来记录手指触摸的EditText的位置
    private int mTouchItemPosition = -1;
    private int mTouchItemPositionTwo = -1;
    //这个bean是为了删除功能而存在的
    private ShopingCartBean delBean;
    private int positionItem;



    public MianShopingCartAdapter(Context context, MianShopingCartFragment fragment){
        this.context =context;
        this.mInflater = LayoutInflater.from(context);
        this.fragment = fragment;
        this.isVisibilityTit = isVisibilityTit;
        listBeans = new ArrayList<ShopingCartBean>();
    }
    @Override
    public int getCount() {
        return listBeans.size();
    }

    @Override
    public Object getItem(int arg0) {
        return arg0;
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
//            if (convertView == null) {
        holder=new ViewHolder();
        convertView = mInflater.inflate(R.layout.item_mian_shoping_cart, null);
        holder.cb_pro_checkbox = (CheckBox) convertView.findViewById(R.id.cb_pro_checkbox);
        holder.txt_name= (TextView) convertView.findViewById(R.id.txt_name);
        holder.image_name= (ImageView) convertView.findViewById(R.id.image_name);
        holder.txt_price= (TextView) convertView.findViewById(R.id.txt_price);
        holder.txt_state= (TextView) convertView.findViewById(R.id.txt_state);
        holder.ll_finish_state= (LinearLayout) convertView.findViewById(R.id.ll_finish_state);
        holder.ll_edit_state= (LinearLayout) convertView.findViewById(R.id.ll_edit_state);
        holder.edit_count = (EditText)convertView.findViewById(edit_count);

        holder.image_del = (ImageView) convertView.findViewById(R.id.image_del);
        holder.image_add = (ImageView) convertView.findViewById(R.id.image_add);
        holder.btn_remove = (Button) convertView.findViewById(R.id.btn_remove);
        holder.txt_num = (TextView) convertView.findViewById(R.id.txt_num);
        holder.txt_goods_attr = (TextView)convertView.findViewById(R.id.txt_goods_attr) ;
        holder.edit_remark = (EditText)convertView.findViewById(R.id.edit_remark);
        holder.layout_item = (LinearLayout)convertView.findViewById(R.id.layout_item);
        holder.edit_count.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                //注意，此处必须使用getTag的方式，不能将position定义为final，写成mTouchItemPosition = position
                mTouchItemPosition = (Integer) view.getTag();
                return false;
            }
        });
        holder.edit_remark.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                //注意，此处必须使用getTag的方式，不能将position定义为final，写成mTouchItemPosition = position
                mTouchItemPositionTwo = (Integer) view.getTag();
                return false;
            }
        });

        convertView.setTag(holder);

//            }else {
//                holder = (ViewHolder)convertView.getTag();
//            }
        final  ShopingCartBean bean = listBeans.get(position);
        holder.txt_name.setText(bean.goods_name);
        holder.txt_price.setText("RM"+bean.goods_price);
        DownloadPicture.loadNetwork(bean.goods_attr_thumb,holder.image_name);
        if (bean.isSelected) {
            holder.cb_pro_checkbox.setChecked(true);
            bean.isSelected = true;
        } else {
            holder.cb_pro_checkbox.setChecked(false);
            bean.isSelected = false;
        }

        holder.cb_pro_checkbox.setOnClickListener(new View.OnClickListener() {
                                                      @Override
                                                      public void onClick(View view) {
                                                          if (bean.isSelected) {
                                                              ((CheckBox)view).setChecked(false);
                                                              bean.isSelected = false;
                                                          } else {
                                                              ((CheckBox)view).setChecked(true);
                                                              bean.isSelected = true;
                                                          }
                                                          fragment.settlementSum();
                                                      }
                                                  }
        );
        holder.txt_state.setOnClickListener(new StateOnClickListener(position,holder.edit_count));
        //当用户点击编辑或者完成
        if (bean.isState) {
            holder.ll_finish_state.setVisibility(View.GONE);
            holder.ll_edit_state.setVisibility(View.VISIBLE);
            holder.btn_remove.setVisibility(View.VISIBLE);
            holder.txt_state.setText(context.getResources().getString(R.string.complete));

        } else {
            holder.ll_finish_state.setVisibility(View.VISIBLE);
            holder.ll_edit_state.setVisibility(View.GONE);
            holder.btn_remove.setVisibility(View.GONE);
            holder.txt_state.setText(context.getResources().getString(R.string.edit));

        }
        int num = Integer.parseInt(bean.goods_number);
        //解决用户点击编辑框修改数量时,没法获取光标
        holder.txt_num.setText("x"+num);
        holder.edit_count.setText(""+num);
        //备注
        holder.edit_remark.setText(bean.remark);
        holder.edit_count.setTag(position);
        if (mTouchItemPosition == position) {
            holder.edit_count.requestFocus();
            holder.edit_count.setSelection( holder.edit_count.getText().toString().length());
        } else {
            holder.edit_count.clearFocus();
        }

        holder.edit_remark.setTag(position);
        if (mTouchItemPositionTwo == position) {
            holder.edit_remark.requestFocus();
            holder.edit_remark.setSelection( holder.edit_remark.getText().toString().length());
        } else {
            holder.edit_remark.clearFocus();
        }


        //用来判断用户是否点击全部编辑
        if (isVisibilityTit) {
            holder.txt_state.setVisibility(View.INVISIBLE);
        } else {
            holder.txt_state.setVisibility(View.VISIBLE);

        }
        //修改商品数量
        holder.image_add.setOnClickListener(new AddOnClickListener(position,holder.edit_count));
        holder.image_del.setOnClickListener(new DelOnClickListener(position,holder.edit_count));
        //删除个别商品
        holder.btn_remove.setOnClickListener(new RemoveOnClickListener(bean));
        holder.txt_goods_attr.setText(bean.goods_attr);
        holder.edit_count.addTextChangedListener(new EditChangedListener(holder.edit_count,position));
        holder.edit_remark.addTextChangedListener(new EditRemarkdListener(holder.edit_remark,position));

        holder.layout_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, CommodityDetActivity.class);
                intent.putExtra("goods_id",bean.goods_id);
                context.startActivity(intent);
            }
        });
        return convertView;
    }
    private  class  ViewHolder {
        CheckBox cb_pro_checkbox;
        TextView txt_price;
        TextView txt_state;
        LinearLayout ll_finish_state,ll_edit_state;
        Button btn_remove;
        EditText edit_count;
        ImageView image_del,image_add;
        TextView txt_num;
        TextView txt_name;
        ImageView image_name;
        TextView txt_goods_attr;
        EditText edit_remark;
        LinearLayout layout_item;
    }

    public void setListBeans(List<ShopingCartBean> listBeans) {
        this.listBeans.clear();
        this.listBeans.addAll(listBeans);
    }

    class StateOnClickListener implements View.OnClickListener {
        int position ;
        EditText edit_count;
        public StateOnClickListener(int position,EditText edit_count) {
            this.position = position;
            this.edit_count = edit_count;
        }
        @Override
        public void onClick(View view) {
            ShopingCartBean bean = listBeans.get(position);
            if (bean.isState) {
                bean.isState = false;
                keyboardUtil.HideKeyboard(edit_count);
                //当用户点击完成的时候，调用接口
                int num = 1;
                String numString = edit_count.getText().toString();
                if (!TextUtils.isEmpty(numString)) {
                    num = Integer.parseInt(edit_count.getText().toString());
                    if (num <= 0) {
                        num = 1;
                    }
                }
                bean.goods_number = num+"";
                positionItem = position;
                alterNumber(bean);
                fragment.settlementSum();
//                  edit_count.clearFocus();
            } else {
                bean.isState = true;
            }
            notifyDataSetChanged();
        }
    }
    //增加数量
    class  AddOnClickListener implements View.OnClickListener {
        int position ;
        EditText edit_count;
        public AddOnClickListener(int position,EditText edit_count) {
            this.position = position;
            this.edit_count = edit_count;
        }
        @Override
        public void onClick(View view) {
            int num = Integer.parseInt(listBeans.get(position).goods_number);
            if (num >= 9999) {
                return;
            }
            int i = num + 1;
            edit_count.setText(i+"");
            listBeans.get(position).goods_number = i+"";
            fragment.settlementSum();
        }
    }
    //减少数量
    class  DelOnClickListener implements View.OnClickListener {
        int position ;
        EditText edit_count;
        public DelOnClickListener(int position,EditText edit_count) {
            this.position = position;
            this.edit_count = edit_count;
        }
        @Override
        public void onClick(View view) {
            int i = Integer.parseInt(listBeans.get(position).goods_number);;
            if (i <= 1) {
                i = 1;
            } else {
                i = i - 1;
            }
            listBeans.get(position).goods_number = i +"";
            edit_count.setText(i+"");
            fragment.settlementSum();
        }
    }

    //删除某个Item
    class  RemoveOnClickListener implements View.OnClickListener {
        ShopingCartBean bean;
        public RemoveOnClickListener(ShopingCartBean bean) {
            this.bean = bean;
        }
        @Override
        public void onClick(View view) {
            delCartData(bean);
        }
    }
    public List<ShopingCartBean> getListBeans() {
        return listBeans;
    }


    public void setLists( List<ShopingCartBean> listBeans) {
        this.listBeans = listBeans;
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result = null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            listBeans.remove(delBean);
                            notifyDataSetChanged();
                            fragment.settlementSum();
                        } else if (state == 1) {
                            U.Toast(context, context.getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(context, context.getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(context, context.getResources().getString(R.string.wdl));
                        }
                    } catch (Exception e) {
                    }
                }
            }
            //修改单个商品数量
            if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            //统一价格
                            listBeans.get(positionItem).initial_number = listBeans.get(positionItem).goods_number;
                        } else if (state == 1) {
                            U.Toast(context, context.getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(context, context.getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(context, context.getResources().getString(R.string.wdl));
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 删除购物车
     */
    public void delCartData(ShopingCartBean delBean) {
        try {
            this.delBean = delBean;
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.DEL_CART;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"rec_id"+delBean.rec_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("rec_id",delBean.rec_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }
    }

    /**
     * 修改单个商品数量接口     */
    public void alterNumber(ShopingCartBean bean) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Map<String,String> map = new HashMap<String, String>();
        map.put("rec_id",bean.rec_id);
        map.put("goods_number",bean.goods_number);
        list.add(map);
        JSONArray jsonArray = new JSONArray(list);

        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.UPDA_CART;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("rec_ids",jsonArray.toString());
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        }catch (Exception e) {

        }
    }

    class EditChangedListener implements TextWatcher {
        private EditText edit_count;
        private int position;
        public EditChangedListener(EditText edit_count,int position) {
            this.edit_count = edit_count;
            this.position = position;

        }
        private CharSequence temp;//监听前的文本
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!TextUtils.isEmpty(edit_count.getText().toString())) {
                int dd = Integer.parseInt(edit_count.getText().toString());
                if (dd > 9999) {
                    edit_count.setText("9999");
                    edit_count.setSelection( edit_count.getText().toString().length());
                }
                if (dd < 1) {
                    if (position < listBeans.size()){
                        listBeans.get(position).goods_number = 1+"";
                    }
                } else {
                    if (position < listBeans.size()){
                        listBeans.get(position).goods_number = edit_count.getText().toString();
                    }
                }
            } else {
                if (position < listBeans.size()){
                    listBeans.get(position).goods_number = 1+"";
                }
            }
        }
    };

    class EditRemarkdListener implements TextWatcher {
        private EditText edit_count;
        private int position;
        public EditRemarkdListener(EditText edit_count,int position) {
            this.edit_count = edit_count;
            this.position = position;

        }
        private CharSequence temp;//监听前的文本
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!TextUtils.isEmpty(edit_count.getText().toString())) {
                if (position < listBeans.size()) {
                    listBeans.get(position).remark = edit_count.getText().toString();
                }
            }
        }
    };
}



